package cn.tannn.ip2region.sdk;

import eu.bitwalker.useragentutils.UserAgent;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * User-Agent工具类
 *
 * @author looly
 *
 */
public class UserAgentUtil {
	private static final Logger LOGGER = LoggerFactory.getLogger(UserAgentUtil.class);
	/**
	 * 解析User-Agent
	 *
	 * @param userAgentString User-Agent字符串
	 * @return {@link UserAgent}
	 */
	public static UserAgent parse(String userAgentString) {
		return UserAgent.parseUserAgentString(userAgentString);
	}


	/**
	 * 解析User-Agent
	 *
	 * @param request User-Agent字符串
	 * @return {@link UserAgent}
	 */
	public static UserAgent parse(HttpServletRequest request) {
		return UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
	}

	/**
	 * 解析User-Agent
	 *
	 * @param request User-Agent字符串
	 * @return 操作系统—浏览器
	 */
	public static String parseStr(HttpServletRequest request) {
		String header = request.getHeader("User-Agent");
		UserAgent userAgent = parse(header);

		String browser = userAgent.getBrowser().getName();
		if(browser.equals("Unknown")) {
			LOGGER.debug(" =======> browser equals Unknown {}", browser);
			// 多了不要
			if (null != header && header.length() > 50) {
				browser = header.substring(0, 50);
			} else {
				browser = header;
			}
		}
		LOGGER.debug(" =======> parseStr UserAgent {}", userAgent);
		return userAgent.getOperatingSystem().getName() + "-" + browser;
	}

}
